<template>
  <div class="container">
    <div class="nav-bar">
      <van-icon name="cross" size="24" color="white" @click="fnToHistory" />
    </div>
    <div class="main">
      <van-tabs @click="onClickTabs" class="tabs">
        <van-tab title="登录">
          <van-form label-width="25%" validate-first @submit="onSubmitLogin" :show-error-message="false">
            <van-field
              v-model="loginForm.loginId"
              label="用户名"
              placeholder="请输入手机号或数字账号"
              :rules="[{ required: true, message: '请填写用户名' }]"
              readonly
              clickable
              :minLength="6"
              @touchstart.native.stop="showObj.showUsernameKeyboard = true"
            />
            <van-number-keyboard
              v-model="loginForm.loginId"
              :show="showObj.showUsernameKeyboard"
              :maxlength="11"
              @blur="showObj.showUsernameKeyboard = false"
            />
            <van-field
              v-model="loginForm.loginPassword"
              type="password"
              label="密码"
              placeholder="请输入密码"
              :rules="[{ required: true, message: '请填写密码' }]"
            />
            <div style="margin: 16px;">
              <van-button round block type="info" native-type="submit">登录</van-button>
            </div>
          </van-form>
        </van-tab>

        <van-tab title="注册">
          <van-form label-width="25%" @submit="onSubmitRegister" validate-first :show-error-message="false">
            <van-field
              v-model="registerForm.mobile"
              label="手机号"
              placeholder="请输入手机号"
              :rules="[{ required: true, message: '请输入手机号' }]"
              readonly
              clickable
              @touchstart.native.stop="showObj.showUsernameKeyboard = true"
            />
            <van-number-keyboard
              v-model="registerForm.mobile"
              :show="showObj.showUsernameKeyboard"
              :maxlength="11"
              @blur="showObj.showUsernameKeyboard = false"
            />
            <van-field
              v-model="registerForm.validCode"
              center
              clearable
              label="短信验证"
              placeholder="请输入短信验证码"
              :maxlength="6"
            >
              <template #button>
                <van-button size="small" type="primary" :disabled="smsBtn.btnDisabled" @click="beforeSendSms()">{{smsBtn.btnText}}</van-button>
              </template>
            </van-field>
            <van-field
              v-model="registerForm.userPassword"
              type="password"
              label="密码"
              placeholder="密码"
              :maxlength="16"
              :rules="[{ required: true, message: '请填写密码' }]"
            />
            <van-field
              v-model="confirmPassword"
              type="password"
              label="确认密码"
              placeholder="请再一次输入密码"
              :maxlength="16"
              :rules="[{ required: true, message: '请填写密码' }]"
            />
            <div style="margin: 16px;">
              <van-button round block type="info" native-type="submit">注册</van-button>
            </div>
          </van-form>
        </van-tab>
      </van-tabs>
    </div>
    <van-dialog title="请先验证" v-model="showObj.showVerify" theme="round-button" show-cancel-button :showConfirmButton="false">
      <slider-verify v-if="showObj.showVerify" @callback="onSliderVerify"></slider-verify>
    </van-dialog>
  </div>
</template>

<script>
  import { loginSendSms, login, getPubKey, registerSendSms, register } from '@/api/login'
  import SliderVerify from '@/components/SliderVerify'
  import NavBar from "@/components/NavBar"
  export default {
    name: "Login",
    components:{SliderVerify, NavBar},
    data() {
      return{
        loginForm: {
          loginId:'',
          loginPassword:'',
          validCode:'',
          tel:''
        },
        registerForm: {
          userPassword:'',
          validCode:'',
          mobile:''
        },
        smsBtn: {
          btnText: "发送验证码",
          btnDisabled: false
        },
        confirmPassword:'',
        showObj: {
          showUsernameKeyboard: false,
          showVerify: false
        },
        pubKey: "",
        tabType: 0
      }
    },
    mounted() {
      this.getLoginPubKey()
    },
    methods: {
      /** 获取数据加密公钥信息 */
      getLoginPubKey() {
        getPubKey().then(res => {
          this.pubKey = res.data.result;
        })
      },
      /** 切换登录操作类型做数据初始化 */
      onClickTabs(name, title){
        this.tabType = name;
        this.Base.clearObj(this.loginForm)
        this.Base.clearObj(this.registerForm)
      },
      /** 发送短信前置校验 */
      beforeSendSms(){
        let tel = this.fnGetTel();

        if(this.Base.isEmpty(tel)){
          this.$toast({
            message: '请填写手机号',
            position: 'bottom',
          });
          return
        }
        if(!this.Base.validateMobile(tel)){
          this.$toast.fail("手机格式不合法");
          return
        }
        this.showObj.showVerify = true;
      },
      /** 短信按钮倒计时 */
      countDownSmsBtn(){
        let _this = this
        _this.smsBtn.btnDisabled = true
        let count = 60;
        let t = setInterval(function () {
          count--
          _this.smsBtn.btnText = "重新发送(" + count+")"
          if(count <= 0){
            _this.smsBtn.btnDisabled = false
            _this.smsBtn.btnText = "发送验证码"
            window.clearInterval(t)
          }
        }, 1000);
      },
      /** 发送短信 */
      sendSms(){
        let tel = this.fnGetTel();
        if(this.tabType == 1) {
          registerSendSms(tel).then(res =>{
            this.countDownSmsBtn()
            this.$toast.success(res.data.result);
          }).catch(e => {
            this.showObj.showVerify = false
          })
        }else {
          // 登录短信
          loginSendSms(tel).then(res =>{
            this.countDownSmsBtn()
            this.$toast.success(res.data.result);
          }).catch(e => {
            this.showObj.showVerify = false
          })
        }
      },
      /** 滑块验证 */
      onSliderVerify(state) {
        if(state){
          this.showObj.showVerify = false
          this.sendSms()
        }
      },
      /** 登录提交 */
      onSubmitLogin(){
        let _this = this
        this.$showLoading()
        const jse = new this.$jsEncrypt()
        jse.setPublicKey(this.pubKey)//配置公钥
        this.loginForm.loginPassword = encodeURIComponent(jse.encrypt(this.loginForm.loginPassword))
        login(this.loginForm).then(res =>{
          this.$hideLoading()
            this.$contactsDB.insert(res.data.result, true, function (result) {
              _this.$router.replace({'name': 'chat'})
            }, function (e) {
              console.log(e)
            })
        }).catch(e => {
          this.loginForm.loginPassword = "";
          this.$hideLoading()
        })
      },
      /** 注册提交 */
      onSubmitRegister(){
        if(!this.Base.validateMobile(this.registerForm.mobile)){
          this.$toast.fail("手机格式不合法！");
          return
        }
        if(this.confirmPassword != this.registerForm.userPassword){
          this.$toast.fail("两次密码不一致！");
          return
        }
        if(this.Base.isEmpty(this.registerForm.validCode) || this.registerForm.validCode.length != 6) {
          this.$toast.fail("请输入验证码！");
          return
        }
        const jse = new this.$jsEncrypt()
        jse.setPublicKey(this.pubKey)//配置公钥
        this.registerForm.userPassword = encodeURIComponent(jse.encrypt(this.registerForm.userPassword))
        register(this.registerForm).then(res => {
          this.$toast.success(res.data.result);
          this.$router.go(0);
        }).catch(e=>{
          this.registerForm.userPassword = "";
        });
      },
      /** 返回上一页 */
      fnToHistory() {
        this.$router.go(-1);
      },
      /** 根据操作类别获取对应手机号 */
      fnGetTel(){
        let tel = '';
        if(this.tabType === 1) {
          tel = this.registerForm.mobile
        }else {
          tel = this.loginForm.tel
        }
        return tel;
      }
    }
  }
</script>

<style scoped>

  .container {
    height: 100%;
    width: 100%;
    background: url("../../assets/login/background.png") fixed center bottom;
    background-size: cover;
  }
  .nav-bar {
    padding: 5% 0 0 6%;
  }
  .main {
    padding: 16% 8% 0 8%;
  }
  .tabs {
    padding: .53333rem 0;
    border-radius: .13333rem;
    background-color: white;
    opacity: 0.85;
  }
</style>